// 6322,2363
/* global BMapGL */
/* global mapv */
/* global mapvgl */
/* global initMap */
import { Camp } from './camp'
import { View, HeatmapLayer, HeatGridLayer } from 'mapvgl'
import { initMap } from '../plugins/common'
import { qtTransPort } from './linkQt'
import { generateLog,printLog, testEvents } from './utils'
import settings from './settings'
import { getLogs } from './log'
import data from '@/mock'
import 'mapvgl/dist/mapvgl.min.js'
import 'bootstrap/dist/css/bootstrap.css'
import './style/index.css'

// 生成并初始化map
const map = initMap({
  tilt: 45,
  heading: 30,
  center: [118.823692, 32.035499],
  zoom: 14,
})
map.setMapStyleV2({
  // styleId: '8d7bd492341c4be4ef9d5a63ddaea58a',
  styleId: '6961aa74021f894e86c4e3fa61e081d0',
})

// 生成并初始化view
const view = new View({
  map: map,
})

// 初始化红、蓝阵营数据
const { red, blue, links } = data
const isMock = settings.mock
const mainLayer = isMock
  ? new Camp([red, blue], links, view, map)
  : new Camp([[], []], [], view, map)
if (!isMock) {
  document.getElementById('tools').style.display = 'none'
}
const isLog = settings.log
if (!isLog) {
  document.getElementById('log').style.display = 'none'
}

console.warn = () => {}

//添加右键菜单
const menu = new BMapGL.ContextMenu()
const txtMenuItem = [
  {
    text: '添加节点',
    callback: function (clickPoint) {
      //map.zoomIn();
      const res = 'point' + ':' + clickPoint.lng + ',' + clickPoint.lat
      qtTransPort(res)
      // mainLayer.addMarker([clickPoint.lng, clickPoint.lat], 0)
    },
  },
]
for (var i = 0; i < txtMenuItem.length; i++) {
  menu.addItem(new BMapGL.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100))
}
map.addContextMenu(menu)

function getLinkLog(isOn, status, coors) {
  const kinds = ['红方发出的干扰线', '蓝方发出的干扰线', '红方发出的通信线', '蓝方发出的通信线'] // 红不同 0 蓝不同  1 红同  2 蓝同 3 代表不同线的种类
  const title = isOn ? '打开动态线：' : '关闭动态线：'
  return [title, `${kinds[status]},起始坐标${coors}`]
}

// 定义暴露在window根目录下的函数
const toolMethods = {
  /**
   *
   * @param {string} name
   * @param {Array} coor
   * @param {number} type
   * @param {number} time
   * @returns
   */
  move(name, coor = [], type = 0, time = 1000) {
    // type: 0 1 2 直线 曲线1 曲线2
    const unit = mainLayer.find('label', name)
    if (!unit || !coor[0]) return
    printLog(generateLog(unit.type, name, 'move'), `经纬度：${coor[0]},${coor[1]}`)
    unit.move(coor, type, time)
  },
  // 暴露出去添加新节点
  addMakernew(type, name, lon, lat) {
    printLog(generateLog(type, name, 'add'), `经纬度：${lon},${lat}`)
    mainLayer.addMarker([lon, lat], type, name)
  },
  // 删除节点
  removemyMaker(name) {
    const unit = mainLayer.find('label', name)
    printLog(`删除了${name}节点:`, unit.coor)
    if (!unit) return
    unit && unit.delNode()
  },
  /*设置红方发射机开关*/
  setRedState(isOn, name, type = 0) {
    const unit = mainLayer.find('label', name)
    printLog(generateLog(unit.type, name, 'setState', isOn), unit.coor)
    if (!unit) return
    if (isOn) {
      unit.openFnalayer(type)
    } else {
      unit.closeFanlayer(type)
    }
  },
  setRedStatezdw(isOn, lng, lat) {
    console.log('存疑')
  },
  setBlueState(isOn, name) {
    const unit = mainLayer.find('label', name)
    printLog(generateLog(unit.type, name, 'setState', isOn), unit.coor)
    if (!unit) return
    if (isOn) {
      unit.openFnalayer()
    } else {
      unit.closeFanlayer()
    }
  },
  setRedFlyLine(isOn, startlng, starlat, endlng, endlat) {
    const options = {
      start: [startlng, starlat],
      end: [endlng, endlat],
    }
    const status = mainLayer.getCampStatus(options)
    if (status == -1) {
      console.log('该经纬度坐标上没有节点，请检查输入') 
      return
    }
    printLog(...getLinkLog(isOn, status, [startlng, starlat, endlng, endlat]))
    const line = {
      ...options,
      status,
    }
    if (isOn) {
      mainLayer.addLinks([line])
    } else {
      mainLayer.delLink(line)
    }
    mainLayer.updateLinkLine()
  },
  setBlueFlyLine(...args) {
    setRedFlyLine(...args)
  },
  insertNet(sourceName, targetName) {
    printLog(`联系线:`,`从${sourceName} 到 ${targetName}`)
    const sUnit = mainLayer.find('label', sourceName)
    const tUnit = mainLayer.find('label', targetName)
    mainLayer.insertNet(sUnit, tUnit)
  },
  interfereNet(sourceName, targetName, time = 1000) {
    printLog(`干扰:`,`从${sourceName} 到 ${targetName}，干扰时间${time}`)
    const unit = mainLayer.find('label', sourceName)
    mainLayer.breakNet(unit, targetName, time)
  },
  setCenter(lng, lat) {
    map.setCenter({ lng, lat })
  },
  uavMap: map,
}
// 注册按钮点击事件
Object.keys(toolMethods).forEach((key) => {
  window[key] = toolMethods[key]
})
isMock && testEvents()

map.addEventListener('click', function (e) {
  const coor = [e.latlng.lng.toFixed(6) * 1, e.latlng.lat.toFixed(6) * 1]
  console.log(coor)
})

const domBtn = document.getElementById('logBtn')
if (domBtn) {
  domBtn.onclick = function () {
    fetch('http://192.168.20.55:8800/log', {
      method: 'POST',
      headers: {
        "Content-Type": "application/json;charset=UTF-8"
      },
      body: JSON.stringify({ info: getLogs() })
    })
  }
}

